<template>
    <el-dialog ref="treeDialog" :visible.sync="isShow" width="1100px" custom-class="dialog-class" append-to-body top="3vh" :fullscreen="fullscreen" @close="handlerClose" :close-on-click-modal="false">
        <div slot="title" class="dialog-title">
            <span>{{title}}</span>
            <i class="s-icon" :class="{
            'el-icon-full-screen': !fullscreen,
            'el-icon-copy-document': fullscreen,
          }" @click="fullscreen = !fullscreen"></i>
        </div>
        <el-container>
            <el-main style="overflow: visible">
                <div class="opera-body">
                    <div class="opera-dept">
                        <div class="opera-title">搜索部门</div>
                        <!--部门数据-->
                        <div class="head-container">
                            <el-input v-model="deptName" size="small" clearable :placeholder="
                    $t('public.placeholder', {
                      placeholder: $t('deptManage.deptName'),
                    })
                  ">
                                <template slot="append">
                                    <span class="dept-serach">
                                        <i class="el-icon-search"></i>
                                        <span>搜索</span>
                                    </span>
                                </template>
                            </el-input>
                        </div>
                        <div class="head-container" style="padding-top:0;">
                            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick">
                                <span class="head-folder-icon" slot-scope="{ node, data }">
                                    <img v-if="(!node.isLeaf && !node.expanded) " src="@/assets/images/icons/icon-folder.png" alt="">
                                    <img v-if="node.expanded && !node.isLeaf" src="@/assets/images/icons/icon-folder-opened.png" alt="">
                                    {{ node.label }}
                                </span>
                            </el-tree>
                        </div>
                    </div>
                    <div class="opera-table">
                        <el-form class="query-form" :model="queryParams" ref="queryForm" label-width="68px" size="small">
                            <el-row>
                                <el-col :span="8">
                                    <el-form-item :label="$t('team.jobnumber')" prop="userCode" size="small">
                                        <el-input v-model="queryParams.userCode" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('team.jobnumber'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item :label="$t('team.jobname')" prop="userName" size="small">
                                        <el-input v-model="queryParams.userName" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('team.jobname'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="8">
                                    <el-form-item :label="$t('team.department')" prop="loginName" size="small">
                                        <el-input v-model="queryParams.loginName" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('team.department'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <div style="text-align: center;margin: 10px 0px 0;">
                                <el-form-item size="small" style="  ">
                                    <el-button class="green-btn" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search") }}</el-button>
                                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("public.reset") }}</el-button>

                                </el-form-item>
                            </div>

                        </el-form>
                        <div class="section-body">

                            <div class="data-wrap">
                                <h5>已添加人员:</h5>
                                <div class="data-content">
                                    <el-tag v-if="single && data &&  data.userName" class="mr10" size="small" :disable-transitions="transition">{{ data.userName }}</el-tag>
                                    <el-tag v-if="data && data.length > 0 && !single" v-for="(item, index) in data" :key="index" class="mr10" size="small" :disable-transitions="transition" closable @close="removeTag(item, index)">{{ item.userName }}</el-tag>
                                    <span v-if="!single && data.length == 0" class="holder-select">请选择</span>
                                    <span v-if="single && !(data && data.userName)" class="holder-select">请选择</span>
                                </div>
                            </div>
                            <el-table max-height="342" border stripe ref="table" :data="tableData" :header-cell-class-name="single?'hideCheckbox':''" @row-click="rowClick" @selection-change="selectionChange" @current-change="handleSelectChange" style="width: 100%">
                                <el-table-column v-if="!single" type="selection" width="55" align="center" />
                                <el-table-column v-if="single" width="55" align="center">
                                    <template slot-scope="scope">
                                        <el-radio v-model="data" :label="scope.row">{{""}}</el-radio>
                                    </template>
                                </el-table-column>
                                <el-table-column :label="$t('public.serialNum')" type="index" align="center">
                                    <template slot-scope="scope">
                                        <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize +
                        scope.$index +
                        1
                      }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="loginName" label="登录名称" align="center" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="userName" label="姓名" align="center" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="dept.deptName" label="部门" align="center" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="status" align="center" label="状态">
                                    <template slot-scope="scope">
                                        {{ scope.row.status == "0" ? "正常" : "停用" }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="email" label="邮箱" show-overflow-tooltip>
                                </el-table-column>
                            </el-table>
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]" :small="true" background style="text-align: right; margin: 8px 0 0" layout=" prev, pager, next, sizes" :total="total">
                            </el-pagination>
                        </div>

                    </div>
                </div>
            </el-main>
            <el-footer height="34px">
                <div class="dialog-footer">
                    <el-button @click="cancel" size="small" icon="el-icon-close">{{
              $t("public.close")
            }}</el-button>
                    <el-button type="primary" @click="submitForm" size="small" icon="el-icon-check">{{ $t("btn.submit") }}</el-button>
                </div>
            </el-footer>
        </el-container>
    </el-dialog>

</template>
<script>
/**
 * 人员按部门多选组件
 * author: fenghuan@enjoysoftware.cn
 * date: 2022/02/16
 * use: <enjoy-person-dropdown v-model="persons"> </enjoy-person-dropdown>
 * person: [{id:1,name:'张三'}, ...]
 */
import { listUser } from '@/api/system/user'
import { treeselect } from '@/api/system/dept'
import { find } from 'lodash'
export default {
    name: 'EnjoyUserTreeDialog',
    props: {
        /* 多选 外部v-model传入的人员 例如：v-model=[{userId:1, userName:'张三'}]  单选 是 {userId:1, userName:'张三'} */
        value: [Object, Array],
        visible: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: '新增人员',
        },
        /** 单选 默认不传为多选 */
        single: {
            type: Boolean,
        },
    },
    data() {
        return {
            fullscreen: false, // 是否全屏
            // 部门树选项
            deptOptions: undefined,
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            // 部门名称
            deptName: undefined,
            data: undefined, //已选择项
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userCode: undefined,
                userName: undefined,
                loginName: undefined,
                deptId: undefined,
            },
            transition: true,
            total: 0, // 表格数据总数
            values: [], // 输入框选择值
            tableData: [], // 表格数据
            inputHeight: 32, //输入框高度
        }
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        singleValue() {
            /** 单选 {userId:... userName:...} */
            let singleValue = {}
            if (this.single && this.value) {
                singleValue = this.value
            }
            return singleValue
        },
    },
    watch: {
        visible(newVal, oldVal) {
            if (newVal) {
                /** 查询部门下拉树结构 */
                this.getTreeselect()
                /** 查询人员列表 */
                this.getList()
            }
        },
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val)
        },
    },
    created() {
        /** 初始化值 */
        this.dataInit()
    },
    mounted() {
        /** 监听文本框内容高度 */
        this.domInit()
    },
    methods: {
        handlerClose(e) {
            this.$emit('update:visible', false)
            this.resetDialog()
        },
        dataInit() {
            /** 初始化值*/
            if (this.single) {
                this.data = this.value
            } else {
                let array = []
                if (Array.isArray(this.value) && this.value.length > 0) {
                    this.value.forEach((value, key) => {
                        array.push({ userId: value.id, userName: value.name })
                    })
                }
                this.values = array
                this.data = [...array]
            }
        },
        domInit() {
            if (!this.single) {
                const self = this
                /** 监听文本框内容高度*/
                const observer = new ResizeObserver((entries) => {
                    entries.forEach((entry) => {
                        const cr = entry.contentRect
                        self.inputHeight = (cr.height || 24) + 8
                    })
                })
                observer.observe(this.$refs.el_select__tags)
            }
        },
        getList() {
            const self = this
            const { data } = self
            listUser(this.queryParams).then((response) => {
                this.tableData = response.rows
                this.total = response.total
                this.$nextTick(function () {
                    if (self.single) {
                        if (data && data.userId) {
                            const tableRow = find(
                                this.tableData,
                                (o) => o.userId == data.userId
                            )
                            this.data = tableRow
                        }
                    } else {
                        if (Array.isArray(data) && data.length > 0) {
                            data.forEach((row, index) => {
                                const tableRow = find(
                                    this.tableData,
                                    (o) => o.userId == row.userId
                                )
                                self.$refs.table.toggleRowSelection(
                                    tableRow || row,
                                    true
                                )
                            })
                        }
                    }
                })
            })
        },
        rowClick(row, column, event) {
            if (this.single) {
                this.$refs.table.clearSelection()
            }
            this.$refs.table.toggleRowSelection(row)
        },
        selectionChange(selection) {
            if (!this.single) {
                this.$nextTick(function () {
                    this.data = selection
                })
            }
        },
        handleSelectChange(row) {
            if (this.single) {
                this.data = row
            }
        },
        handleSizeChange(size) {
            this.queryParams.pageSize = size
            this.getList()
        },
        handleCurrentChange(page) {
            this.queryParams.pageNum = page
            this.getList()
        },
        remove(row, index) {
            this.values.splice(index, 1)
            this.$refs.table.toggleRowSelection(row, false)
        },
        removeTag(row, index) {
            this.data.splice(index, 1)
            this.$refs.table.toggleRowSelection(row, false)
        },
        /* 输出外部的数据，例如：[{id:1,name:'张三'}] */
        exportData(data) {
            let array = []
            if (Array.isArray(data)) {
                forEach(data, (value, key) => {
                    array.push({ id: value.userId, name: value.userName })
                })
            }
            return array
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id
            this.getList()
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data
            })
        },
        cancel() {
            this.handlerClose()
        },
        submitForm() {
            if (!this.single) {
                this.values = [...this.data]
            }
            this.$emit('input', this.data)
            this.$emit('change', this.data)
            this.handlerClose()
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        resetDialog() {
            this.deptName = undefined
            this.data = []
            this.resetForm('queryForm')
            this.$refs.table.clearSelection()
        },
    },
}
</script>

<style scoped>
.dialog-title {
    width: calc(100% - 20px);

    display: flex;
    align-items: center;
    justify-content: space-between;
}
.dialog-title span {
    font-size: 14px;
}
::v-deep .el-dialog__header .el-dialog__headerbtn {
    top: 10px;
}
.data-content {
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    padding: 3px 10px 3px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    min-height: 30px;
    box-sizing: border-box;
}
.data-content .el-tag {
    background-color: white;
    border-color: #ededf2;
    color: #535862;
    padding: 0 10px;
    margin: 1px 10px 1px 0 !important;
    line-height: 19px;
    border-radius: 2px;
}
.data-content ::v-deep .el-tag .el-tag__close {
    color: #535862;
    font-size: 16px;
    vertical-align: -3px;
}
.data-content ::v-deep .el-tag .el-tag__close:hover {
    background-color: transparent;
}
::v-deep .el-dialog__body {
    padding: 10px 24px;
    height: 524px;
}
.data-wrap {
    margin-bottom: 10px;
}
.data-wrap h5 {
    margin: 0;
    line-height: 30px;
    font-weight: bold;
}
.opera-body {
    display: flex;
    height: 100%;
}
.opera-dept {
    width: 240px;
    margin-right: 10px;
    flex-shrink: 0;
    border-radius: 4px;
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.15);
}
.opera-title {
    padding: 0 10px;
    height: 30px;
    line-height: 30px;
    color: #333;
    font-size: 12px;
    border-bottom: 1px solid #e5e5e5;
    font-weight: 600;
}
.head-container {
    padding: 10px;
}
.opera-table {
    width: 805px;
}
.opera-table ::v-deep .el-form-item__label {
    font-size: 12px;
}
.query-form {
    padding: 20px 10px !important;
    border-radius: 4px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
}
::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 0;
}
::v-deep .data-content .el-tag {
    margin: 3px 10px 3px 0;
}
::v-deep .dialog-class {
    height: 700px !important;
}
.dialog-footer {
    text-align: center;
    margin: 10px 0;
}

::v-deep .el-header,
::v-deep .el-main,
::v-deep .el-footer {
    padding: 0;
}
::v-deep .el-main {
    overflow-x: hidden;
}
::v-deep .el-header {
    height: auto !important;
}
::v-deep .el-footer {
    padding-top: 7px;
}
::v-deep .el-container {
    height: 504px;
}
::v-deep .el-dropdown,
::v-deep .el-select {
    display: block;
}
.holder-select {
    color: #c6c6c6;
    font-size: 12px;
}
.section-body {
    padding: 0 10px 10px 10px;
    margin-top: 10px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
}
.green-btn {
    background-color: #20b09f;
    border: 1px solid #20b09f;
}
::v-deep .el-input-group__append {
    background-color: var(--current-color);
    color: white;
    cursor: pointer;
}

.head-folder-icon img {
    display: inline-block;
    width: 12px;
    height: 12px;
}
::v-deep .hideCheckbox .el-checkbox {
    display: none;
}
</style>
